import { prisma } from '../db'
import type { User, UserRole } from '@prisma/client'

export interface CreateUserData {
  email: string
  username: string
  password?: string
  role?: UserRole
  googleId?: string
  avatar?: string
}

export class UserService {
  /**
   * 创建新用户
   */
  static async createUser(data: CreateUserData): Promise<User> {
    return await prisma.user.create({
      data: {
        email: data.email,
        username: data.username,
        password: data.password,
        role: data.role || 'USER',
        googleId: data.googleId,
        avatar: data.avatar
      }
    })
  }

  /**
   * 根据 ID 获取用户
   */
  static async getUserById(id: number): Promise<User | null> {
    return await prisma.user.findUnique({
      where: { id }
    })
  }

  /**
   * 根据邮箱获取用户
   */
  static async getUserByEmail(email: string): Promise<User | null> {
    return await prisma.user.findUnique({
      where: { email }
    })
  }

  /**
   * 根据用户名获取用户
   */
  static async getUserByUsername(username: string): Promise<User | null> {
    return await prisma.user.findUnique({
      where: { username }
    })
  }

  /**
   * 更新用户信息
   */
  static async updateUser(id: number, data: Partial<Omit<User, 'id' | 'createdAt' | 'updatedAt'>>): Promise<User> {
    return await prisma.user.update({
      where: { id },
      data
    })
  }

  /**
   * 根据Google ID获取用户
   */
  static async getUserByGoogleId(googleId: string): Promise<User | null> {
    return await prisma.user.findUnique({
      where: { googleId }
    })
  }

  /**
   * 激活/停用用户
   */
  static async toggleUserStatus(id: number, isActive: boolean): Promise<User> {
    return await prisma.user.update({
      where: { id },
      data: { isActive }
    })
  }

  /**
   * 获取用户的充值记录
   */
  static async getUserRechargeRecords(userId: number, page: number = 1, limit: number = 20) {
    const skip = (page - 1) * limit

    const [records, total] = await Promise.all([
      prisma.rechargeRecord.findMany({
        where: { userId },
        skip,
        take: limit,
        orderBy: { createdAt: 'desc' }
      }),
      prisma.rechargeRecord.count({
        where: { userId }
      })
    ])

    return {
      records,
      total,
      page,
      totalPages: Math.ceil(total / limit)
    }
  }

  /**
   * 删除用户
   */
  static async deleteUser(id: number): Promise<User> {
    return await prisma.user.delete({
      where: { id }
    })
  }

  /**
   * 获取所有用户
   */
  static async getAllUsers(): Promise<User[]> {
    return await prisma.user.findMany({
      orderBy: { createdAt: 'desc' }
    })
  }
}
